/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["shequ", class {
    constructor() {
        this.page = this.getUrlPage(); // 当前页数
        this.postData = null; // 帖子数据
        this.search = this.getSearch(); // 搜索内容
        this.partitionName = this.getPartition(); // 帖子分区名
        // 缓存一些常用的选择器
        this.cacheSelectors();
    };
    
    // 缓存常用的jQuery选择器结果以提高性能
    cacheSelectors() {
        this.$appShequPartition = $('.app-shequ-partition');
        this.$appMainContentItemMpa = $('.app-main-content-item-mpa');
        this.$appShequPartitionAbs = $('.app-shequ-partition-abs');
    }
    
    init_(require) { // 全局初始化
        const { resize, dateSpanString, pushStateWithSearchParams } = require("index");
        const { loadPostsByData } = require("postlist");

        this.resize = resize;
        this.dateSpanString = dateSpanString;
        this.pushStateWithSearchParams = pushStateWithSearchParams;
        this.loadPostsByData = loadPostsByData.bind(require("postlist"));

        this.getPostData();
        this.getPartitionData();
        this.resetPartitionPosition();
        this.initSearch();
        this.initPartitionStateHistory();
    };

    // —————————————————————————— 帖子&分页 ——————————————————————————
    loadPostStart() { // 加载开始
        $(".app-cards").attr("load", "").html("").append($("<p class='load'>加载中</p>"));
        $(".app-main-pages").html("");
        this.resize();
    };
    loadPostEnd() {  // 加载结束
        $(".app-cards").removeAttr("load", "").find("p.load").remove();
        this.resize();
    };
    loadPostError(msg) { // 加载出错
        this.loadPostEnd();
        $(".app-cards").attr("load", "").attr("error", "").append($("<p>").text(msg || '加载出错'));
        this.resize();
    };
    getPostData() { // 获取数据
        this.loadPostStart();
        if (this.search) {
            this.searchOpen();
            $.ajax('/api/shequ/search_post/' + this.page + "?t=" + Date.now() + "&key_word=" + encodeURIComponent(this.search), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) { // 如果状态码为200
                    this.postData = response.data;

                    this.loadPostEnd();
                    this.renderPost();
                    this.renderPages();
                } else {
                    this.loadPostError(response.msg);
                }
            }).fail(() => {
                this.loadPostError();
            });
        } else {
            this.searchClose();
            $.ajax('/api/shequ/get_post_list/' + this.page + '/' + this.partitionName + "?t=" + Date.now(), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) { // 如果状态码为200
                    this.postData = response.data;

                    this.loadPostEnd();
                    this.renderPost();
                    this.renderPages();
                } else {
                    this.loadPostError(response.msg);
                }
            }).fail(() => {
                this.loadPostError();
            });
        }
    };
    renderPost() { // 渲染帖子
        var data = this.postData.data;
        var cards = $('.app-cards');
        this.loadPostsByData(data, cards);
        this.resize();
    };
    renderPages() { // 渲染分页
        $(".app-main-pages").html("");

        var page = this.page; // 当前页
        var size = this.postData.size; // 总页数
        var omit = true; // 是否省略

        // 添加向左翻页按钮
        var left = $(`<button class="left">&lt;</button>`)
        left.appendTo($(".app-main-pages"));

        for (let i = 0; i < size; i++) {
            let toadd = false; // 是否要添加页数按钮

            if (i === 0) toadd = true; // 第一页要添加
            if (i === size - 1) toadd = true; // 最后一页要添加
            if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
            if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
            if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

            if (toadd) {
                // 渲染页数按钮
                let button = $(`<button class="${(i + 1) == page ? `active` : ""} page-num">${i + 1}</button>`);
                button.on("click", () => { // 点击事件
                    this.goToTop();
                    this.changePage(Number(i + 1));
                })
                button.appendTo($(".app-main-pages"));
                omit = true;
            } else {
                if (omit) {
                    $(`<button disabled>...</button>`).appendTo($(".app-main-pages"));
                    omit = false;
                }
            }
        }

        // 添加向右翻页按钮
        var right = $(`<button class="right">&gt;</button>`)
        right.appendTo($(".app-main-pages"));

        // 根据条件禁用按钮
        left.prop("disabled", page === 1);
        right.prop("disabled", page === size)

        // 添加点击事件
        left.on("click", () => { // 向左
            this.changePage(this.page - 1);
        })

        right.on("click", () => { // 向右
            this.changePage(this.page + 1);
        })

        this.resize();
    };
    goToTop() { // 回到顶部
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    };
    changePage(page) { // 更改页面
        this.page = Number(page) || 1;
        this.pushStateWithSearchParams({
            p: this.page
        });
        this.getPostData();
    };
    getUrlPage() { // 获取链接中的页面参数
        return Number(new URL(location.href).searchParams.get("p")) || 1;
    };

    // —————————————————————————— 分区加载 ——————————————————————————
    // 获取分区数据
    getPartitionData() { // 获取数据
        var loadingText = $("<p class='partition-loading'>加载中</p>");
        loadingText.appendTo(this.$appShequPartition);

        $.ajax('/api/shequ/get_post_partition/?t=' + Date.now(), {
            contentType: 'application/json',
        }).done(response => {
            loadingText.remove();

            if (response.code == 200) { // 如果状态码为200
                // 清空现有的分区内容，但保留"发布实验"按钮和分隔线
                const publishButton = this.$appShequPartition.find('a:first-child');
                const separator = this.$appShequPartition.find('hr:first');
                
                // 清空容器
                this.$appShequPartition.empty();
                
                // 重新添加发布实验按钮和分隔线
                if (publishButton.length > 0) {
                    this.$appShequPartition.append(publishButton);
                } else {
                    // 如果没有发布实验按钮，则创建一个
                    const newPublishButton = $('<a href="/shequ/sendpost" class="publish-btn">发布实验</a>');
                    this.$appShequPartition.append(newPublishButton);
                }
                
                if (separator.length > 0) {
                    this.$appShequPartition.append(separator);
                } else {
                    // 如果没有分隔线，则创建一个
                    this.$appShequPartition.append('<hr class="partition-separator">');
                }
                
                // 创建一个新容器来存放分区树
                const treeContainer = $('<div class="partition-tree-container"></div>');
                this.$appShequPartition.append(treeContainer);
                
                // 清空移动端容器
                this.$appMainContentItemMpa.empty();
                
                // 处理树状结构数据
                var treeData = this.processTreeData(response.data);
                
                // 添加"全部实验"作为根节点
                var rootNode = {
                    id: 'all',
                    name: '全部实验',
                    level: 0,
                    children: treeData
                };
                
                // 渲染电脑端的可折叠分区树
                this.renderPartitionTreeDesktop(rootNode, 0, treeContainer);
                
                // 渲染移动端的扁平化分区列表
                var flatList = this.flattenTree(rootNode);
                this.renderPartitionListMobile(flatList);

                this.updatePartitionActive();
                
                // 默认展开当前选中分区的父节点
                this.expandActivePartition();
            } else {
                this.$appShequPartition.append($("<p class='partition-error'>").text(response.msg || '加载出错'));
            }
        }).fail(() => {
            this.$appShequPartition.append("<p class='partition-error'>加载出错</p>");
        });
    };
    
    // 处理从后端获取的树状数据
    processTreeData(treeData) {
        var result = [];
        
        // 添加检查确保treeData是对象
        if (!treeData || typeof treeData !== 'object') {
            return result;
        }
        
        // 将对象格式的树转换为数组格式
        for (var key in treeData) {
            if (treeData.hasOwnProperty(key)) {
                var node = treeData[key];
                if (node && typeof node === 'object') {
                    // 确保节点有id和name属性
                    if (!node.id) node.id = key;
                    if (!node.name) node.name = '未命名分区';
                    
                    // 递归处理子节点
                    if (node.children && typeof node.children === 'object') {
                        node.children = this.processTreeData(node.children);
                    } else {
                        node.children = [];
                    }
                    
                    result.push(node);
                }
            }
        }
        
        return result;
    }
    
    // 将树状结构扁平化为列表
    flattenTree(node, level = 0) {
        var result = [];
        
        if (!node || typeof node !== 'object') {
            return result;
        }
        
        result.push({
            id: node.id || '',
            name: node.name || '未命名',
            level: level
        });
        
        // 递归处理子节点
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
            node.children.forEach(child => {
                result = result.concat(this.flattenTree(child, level + 1));
            });
        }
        
        return result;
    }
    
    // 渲染电脑端的可折叠分区树
    renderPartitionTreeDesktop(node, level, container) {
        // 为不同层级添加不同的缩进样式
        const indent = level * 20;
        
        // 创建节点容器并设置data-level属性
        const nodeContainer = $('<div class="partition-node-container" data-level="' + level + '"></div>');
        nodeContainer.css('padding-left', `${indent}px`);
        
        // 如果有子节点，添加折叠/展开按钮
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
            const toggleBtn = $('<span class="toggle-btn">+</span>');
            nodeContainer.append(toggleBtn);
            
            // 创建子节点容器
            const childrenContainer = $('<div class="partition-children-container"></div>');
            childrenContainer.hide(); // 默认折叠
            
            // 绑定折叠/展开事件，添加动画效果
            toggleBtn.on('click', function(e) {
                e.stopPropagation(); // 阻止事件冒泡
                childrenContainer.slideToggle(200);
                $(this).toggleClass('expanded');
                $(this).text(childrenContainer.is(':visible') ? '-' : '+');
            });
            
            // 递归渲染子节点
            const self = this;
            node.children.forEach(function(child) {
                self.renderPartitionTreeDesktop(child, level + 1, childrenContainer);
            });
            
            nodeContainer.append(childrenContainer);
        } else {
            // 如果没有子节点，添加占位符以保持对齐
            const placeholder = $('<span class="toggle-btn placeholder"></span>');
            nodeContainer.append(placeholder);
        }
        
        // 创建节点按钮
        const nodeBtn = $('<button class="partition-node"></button>');
        nodeBtn.text(node.name || '未命名');
        nodeBtn.attr('pa', node.id || '');
        
        // 添加层级特定样式
        if (level === 0) {
            nodeBtn.addClass('root-node');
        } else if (level === 1) {
            nodeBtn.addClass('level-1');
        } else {
            nodeBtn.addClass('level-deep');
        }
        
        // 绑定点击事件
        nodeBtn.on('click', () => {
            this.pushStateWithSearchParams({
                pa: node.id || '',
                p: 1
            });
            this.updatePartition();
        });
        
        // 添加到节点容器
        nodeContainer.append(nodeBtn);
        
        // 添加到指定的父容器
        container.append(nodeContainer);
    };
    
    // 渲染移动端的扁平化分区列表
    renderPartitionListMobile(partitionArray) {
        // 确保partitionArray是数组
        if (!Array.isArray(partitionArray)) {
            return;
        }
        
        // 添加标题
        const mobileTitle = $('<div class="mobile-partition-title">选择分区</div>');
        this.$appMainContentItemMpa.append(mobileTitle);
        
        // 创建滚动容器，处理较多分区的情况
        const scrollContainer = $('<div class="mobile-partition-scroll"></div>');
        this.$appMainContentItemMpa.append(scrollContainer);
        
        partitionArray.forEach(partition => {
            if (!partition) return;
            
            let btn = $("<button class='mobile-partition-btn'></button>");
            
            // 为子分区添加缩进标记
            let indentText = '';
            if (partition.level > 0) {
                indentText = '  '.repeat(partition.level);
            }
            
            // 确保partition.name存在
            const partitionName = partition.name || '未命名';
            btn.text(indentText + partitionName);
            btn.attr('pa', partition.id || '');
            
            // 添加层级样式
            if (partition.level === 0) {
                btn.addClass('mobile-root');
            } else if (partition.level === 1) {
                btn.addClass('mobile-level-1');
            }
            
            // 绑定点击事件
            btn.on('click', () => {
                this.pushStateWithSearchParams({
                    pa: partition.id || '',
                    p: 1
                });
                this.updatePartition();
            });
            
            scrollContainer.append(btn);
        });
    };
    
    // 展开当前选中分区的所有父节点
    expandActivePartition() {
        const activeBtn = this.$appShequPartition.find(`.partition-node[pa="${this.partitionName}"]`);
        if (!activeBtn.length) return;
        
        // 找到所有祖先节点容器
        let parentContainer = activeBtn.closest('.partition-children-container');
        
        // 向上遍历并展开所有父节点
        while (parentContainer.length) {
            const toggleBtn = parentContainer.prev('.toggle-btn');
            if (toggleBtn.length && !parentContainer.is(':visible')) {
                toggleBtn.click(); // 触发点击事件来展开
            }
            parentContainer = parentContainer.parent('.partition-node-container').closest('.partition-children-container');
        }
    }
    
    updatePartitionActive() {
        // 清除所有active状态
        this.$appShequPartition.find('.partition-node').removeClass('active');
        this.$appMainContentItemMpa.find('.mobile-partition-btn').removeClass('active');
        
        // 设置当前分区为active
        this.$appShequPartition.find(`.partition-node[pa="${this.partitionName}"]`).addClass('active');
        this.$appMainContentItemMpa.find(`.mobile-partition-btn[pa="${this.partitionName}"]`).addClass('active');
    };
    
    getPartition() { // 获取分区
        return new URL(location.href).searchParams.get("pa") || "all";
    };
    
    updatePartition() { // 切换分区
        this.partitionName = this.getPartition();
        this.updatePartitionActive();
        this.changePage(1);
    };
    
    resetPartitionPosition() { // 重新规划分区栏位置
        if ($(window).scrollTop() >= 50) {
            this.$appShequPartition.addClass("fixed");
        } else {
            this.$appShequPartition.removeClass("fixed");
        }
        requestAnimationFrame(this.resetPartitionPosition.bind(this));
    };
    
    initPartitionStateHistory() {
        $(window).on('popstate', () => {
            if (this.getPartition() != this.partitionName) {
                this.updatePartition();
            }
        })
    };

    // —————————————————————————— 搜索加载 ——————————————————————————
    initSearch() {
        var input = $(".app-main-content-item-search-input");
        var btn = $(".app-main-content-item-search-btn");
        var back = $(".app-main-content-item-search-back");

        input.val(this.search);

        // 内容更新时，如果为空则禁用按钮
        input.on("input", () => {
            if (input.val() == "") btn.attr("disabled", "");
            else btn.removeAttr("disabled");
        });

        // 按钮点击搜索
        btn.on("click", () => {
            if (input.val() == "") return;
            this.changeSearch(input.val());
        });

        // 在输入框聚集时按下回车也触发搜索
        input.on("keydown", (e) => {
            if (e.keyCode == 13) {
                if (input.val() == "") return;
                this.changeSearch(input.val());
            }
        });

        // 返回按钮点击时清空搜索内容
        back.on("click", () => {
            input.val("");
            this.changeSearch("");
        });
    };
    
    changeSearch(search) {
        this.search = search;
        this.pushStateWithSearchParams({
            pa: null,
            sr: this.search ? encodeURIComponent(this.search) : null,
            p: 1
        });
        this.updatePartition();
    };
    
    searchOpen() {
        this.$appShequPartitionAbs.hide();
        this.$appMainContentItemMpa.addClass("hide");
        $(".app-main-content-item-search-back").show();
        $(".app-main-content-item-title span").hide();
    };
    
    searchClose() {
        this.$appShequPartitionAbs.show();
        this.$appMainContentItemMpa.removeClass("hide");
        $(".app-main-content-item-search-back").hide();
        $(".app-main-content-item-title span").show();
    };
    
    getSearch() { // 获取链接中的搜索参数
        return decodeURIComponent(new URL(location.href).searchParams.get("sr") || "") || "";
    };
}])
